package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.dto.MobileOrderDto;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.service.SetMealService;
import com.itheima.health.vo.OrderSubmitParam;
import io.swagger.annotations.Api;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 预约控制器
 */
@RestController
@RequestMapping("/mobile/order")
@Slf4j
@Api(tags = "手机端订单接口")
public class MobileOrderController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderSettingService orderSettingService;
    @Autowired
    private SetMealService setMealService;

    @PostMapping("/submit")
    public Result submit(@RequestBody Map<String, String> data, HttpServletResponse response) {
        log.info("[手机端订单-提交]" + data);
        //检查验证码是否正确
        String telephone = data.get("telephone");
        String validateCode = data.get("validateCode");
        if (Objects.equals(validateCode, "") && Objects.equals(telephone, "")) {//手机号和验证码都不能为空
            return new Result(false, MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        String redisVCode = (String) redisTemplate.opsForValue().get(telephone);

        if (!validateCode.equals(redisVCode)) {//判断验证是否失败
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
        //验证成功删除redis验证码
        Boolean delete = redisTemplate.delete(telephone);
        //System.out.println(delete);

        //获取并封装会员信息,如果会员不存在,自动注册
        Member member = memberService.selectByPhoneNumber(telephone);
        if (member == null) {
            member = new Member();
            member.setIdCard(data.get("idCard"));
            member.setSex(data.get("sex"));
            member.setName(data.get("name"));
            member.setPhoneNumber(data.get("telephone"));
            member.setRegTime(new Date());
            memberService.register(member);
        }
        String strOrderDate = data.get("orderDate");
        //如果会员存在,当天不能重复预约
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<Order> orders = orderService.selectByMemberid(member.getId());
        if (orders != null) {
            for (Order order : orders) {
                if (format.format(order.getOrderDate()).equals(strOrderDate)) {
                    return new Result(false,MessageConst.HAS_ORDERED);
                }
            }
        }

        //获取并封装订单信息
        Order order = new Order();
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(Integer.valueOf(data.get("setmealId")));
        Date orderDate;
        try {
            orderDate = format.parse(data.get("orderDate"));
        } catch (ParseException e) {
            return new Result(false, MessageConst.SELECTED_DATE_CANNOT_ORDER);
        }
        order.setOrderDate(orderDate);

        order.setMemberId(member.getId());
        orderService.add(order);
//体检预约是否已经约满
        OrderSetting orderSetting= orderSettingService.selectByDate(orderDate);
        if(orderSetting==null){
            throw new BusinessRuntimeException("预约日期为设置!");
        }
        if(orderSetting.getNumber()<=orderSetting.getReservations()){
            return new Result(false,MessageConst.ORDER_FULL);
        }



        return new Result(true, MessageConst.ORDER_SUCCESS,member);
    }


    //展示预约的相关信息
    @GetMapping("/findById")
    public Result findById(Integer id){
        MobileOrderDto mobileOrderDto = new MobileOrderDto();
        Order order = orderService.findById(id);
        log.info("打印获取到的对象OrderType"+order.getOrderType());
        log.info("打印获取到的对象getOrderDate"+order.getOrderDate());
        mobileOrderDto.setOrderType(order.getOrderType());
        mobileOrderDto.setOrderDate(order.getOrderDate());
        Integer setmealId = order.getSetmealId();
        log.info("打印获取到的对象id"+setmealId);
        Setmeal setmeal = setMealService.selectId(setmealId);
        mobileOrderDto.setSetmeal(setmeal.getName());

        Member member = memberService.findById(order.getMemberId());
        mobileOrderDto.setMember(member.getName());

        return new Result(true,MessageConst.QUERY_ORDER_SUCCESS,mobileOrderDto);
    }

}
